<template>
  <div id="image_exam">
    <CommonTable
      :query-api="'/workStation/exam/page'"
      :query-params="param"
      :columns="columns"
      query-store="image_params"
      @search-finish="searchFinish"
      ref="imageRef"
      name="image_exam"
    >
      <template #tableSearchForm>
        <div>
          <a-form id="internal_form_model" :model="formInfo" layout="inline">
            <a-form-item label="检查时间">
              <DateRange
                :format="'YYYY-MM-DD HH:mm:ss'"
                :dateRange="15"
                @changeRange="(dateList) => changeRange(dateList, 'examTime')"
                ref="examTimeRef"
              ></DateRange>
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="onSerach" :loading="loading" :disabled="loading"
                  >查看结果</a-button
                >
                <a-button type="primary" @click="onSerach" :loading="loading" :disabled="loading"
                  >查询</a-button
                >
                <a-button @click="resetForm" :loading="loading" :disabled="loading">重置</a-button>
                <a-button click="resetForm" @click="updateOpen()">
                  <span v-show="isOpen">
                    <UpOutlined />
                    收起
                  </span>
                  <span v-show="!isOpen">
                    <DownOutlined />
                    展开
                  </span>
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
          <!-- <div v-if="!isOpen" style="padding: 0px 10px; font-size: 12px">
            <span v-if="selectContentList.length">查询内容：</span>
            <span v-for="(item, index) in selectContentList" :key="index"
              >{{ item.title }}{{ item.value }}
              <span style="padding: 0px 5px" v-if="index + 1 < selectContentList.length"
                >/</span
              ></span
            >
          </div> -->
          <a-drawer
            wrapClassName="common_search_drawer"
            title="科内报告质控"
            placement="left"
            @close="updateOpen"
            :closable="false"
            v-model:open="isOpen"
            :width="560"
          >
            <a-form
              id="internal_drawer_form_model"
              :model="formInfo"
              :label-col="{ span: 4 }"
              :wrapper-col="{ span: 20 }"
            >
              <a-form-item label="检查时间">
                <DateRange
                  :format="'YYYY-MM-DD HH:mm:ss'"
                  :dateRange="15"
                  @changeRange="(dateList) => changeRange(dateList, 'examTime')"
                  ref="examTimeCopyRef"
                  style="width: 100%"
                ></DateRange>
              </a-form-item>
              <a-form-item label="质控医生">
                <a-select
                  v-model:value="formInfo.scoreUserId"
                  style="width: 100%"
                  popupClassName="common_select_dropdown"
                  allowClear
                  show-search
                  :filter-option="filterOption"
                >
                  <a-select-option
                    v-for="item in qcDrList"
                    :key="item.id"
                    :value="item.id"
                    :desc="item.desc"
                  >
                    {{ item.desc }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="质控状态">
                <a-select
                  v-model:value="formInfo.scoreStatus"
                  style="width: 100%"
                  popupClassName="common_select_dropdown"
                >
                  <a-select-option
                    v-for="item in ScoreStatusEnum"
                    :value="item.value"
                    :key="item.value"
                    >{{ item.label }}</a-select-option
                  >
                </a-select>
              </a-form-item>
              <a-form-item label="会诊状态">
                <a-select
                  v-model:value="formInfo.rcStatus"
                  style="width: 100%"
                  popupClassName="common_select_dropdown"
                >
                  <a-select-option
                    v-for="item in RcStatusEnum"
                    :value="item.value"
                    :key="item.value"
                    >{{ item.label }}</a-select-option
                  >
                </a-select>
              </a-form-item>
              <a-form-item label="阴阳性">
                <a-select
                  v-model:value="formInfo.positive"
                  style="width: 100%"
                  popupClassName="common_select_dropdown"
                >
                  <a-select-option :value="''" :key="''">全部</a-select-option>
                  <a-select-option :value="'false'" :key="'false'">阴性</a-select-option>
                  <a-select-option :value="'true'" :key="'true'">阳性</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="患者信息">
                <a-input
                  v-model:value="formInfo.patInfo"
                  placeholder="患者姓名/检查号"
                  allowClear
                  style="width: 100%"
                ></a-input>
              </a-form-item>
              <a-form-item label="性别">
                <a-select
                  v-model:value="formInfo.patSex"
                  style="width: 100%"
                  popupClassName="common_select_dropdown"
                  allowClear
                >
                  <a-select-option v-for="item in sexList" :key="item.value" :value="item.label">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="检查医院">
                <a-select
                  v-model:value="formInfo.hospId"
                  allowClear
                  style="width: 100%"
                  popupClassName="common_select_dropdown"
                  @change="hospChange"
                >
                  <a-select-option v-for="item in hospList" :value="item.id" :key="item.id">{{
                    item.desc
                  }}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="检查诊室">
                <a-select
                  v-model:value="formInfo.deptGUID"
                  allowClear
                  style="width: 100%"
                  popupClassName="common_select_dropdown"
                >
                  <a-select-option v-for="item in teamList" :value="item.value" :key="item.value">{{
                    item.label
                  }}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="完成医生">
                <a-select
                  v-model:value="formInfo.finishDrId"
                  style="width: 100%"
                  popupClassName="common_select_dropdown"
                  allowClear
                  show-search
                  :filter-option="filterOption"
                >
                  <a-select-option
                    v-for="(item, index) in finishDrList"
                    :key="index"
                    :value="item.value"
                    :label="item.label"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="评分时间">
                <DateRange
                  :format="'YYYY-MM-DD HH:mm:ss'"
                  :dateRange="15"
                  @changeRange="(dateList) => changeRange(dateList, 'scoreTime')"
                  ref="scoreTimeRef"
                  style="width: 100%"
                ></DateRange>
              </a-form-item>
              <a-form-item
                class="filter_footer"
                :label-col="{ span: 0 }"
                :wrapper-col="{ span: 24 }"
              >
                <a-space>
                  <a-button type="primary" @click="onSerach" :loading="loading" :disabled="loading"
                    >查询</a-button
                  >
                  <a-button @click="resetForm" :loading="loading" :disabled="loading"
                    >重置</a-button
                  >
                  <a-button click="resetForm" @click="updateOpen()">
                    <span v-show="isOpen">
                      <UpOutlined />
                      收起
                    </span>
                    <span v-show="!isOpen">
                      <DownOutlined />
                      展开
                    </span>
                  </a-button>
                </a-space>
              </a-form-item>
            </a-form>
          </a-drawer>
        </div>
      </template>
      <template #otherAction="{ record }">
        <a-button @click="enterMark(record)">质控</a-button>
      </template>
    </CommonTable>
  </div>
</template>
<script lang="ts" setup>
import CommonTable from '@/components/common_table/index.vue'
import type { TColumn } from '@/components/common_table/type'
import DateRange from '@/components/common_date_range/index.vue'
import {
  getTeamList,
  getFinishDrList,
  getHospList,
  getSexList,
  getQcDrList
} from '@/axios/api/options_api'

import type { OptionsType, ListType } from '@/axios/api/type'
import { RcStatusEnum } from '@/enums/rc_status_enum'
import { ScoreStatusEnum } from '@/enums/score_status_enum'
import { UpOutlined, DownOutlined } from '@ant-design/icons-vue'
import storageUtil from '@/utils/storage_util'
import { filterOption } from '@/utils/filter_util'
import { ref, h, onMounted, computed, watch, onBeforeUnmount } from 'vue'
import type { FromType } from './type.ts'
import { cloneDeep } from 'lodash-es'
import moment from 'moment'
const scoreTimeRef = ref()
const examTimeRef = ref()
const examTimeCopyRef = ref()
const imageRef = ref()
const columns = ref<TColumn[]>([
  {
    title: '姓名', // 名称
    align: 'center', // 居中
    dataIndex: 'patName', // 表格数据对应的列
    key: 'patName', // 唯一标识
    width: 110, // 宽度
    ellipsis: true, // 文字超出宽度影藏
    showCol: true,
    fixed: 'left' // 固定到左边
  },
  {
    title: '性别',
    align: 'center',
    width: 70,
    dataIndex: 'patSex',
    key: 'patSex',
    showCol: true,
    fixed: 'left'
  },
  {
    title: '检查项目',
    align: 'left',
    dataIndex: 'eitemNames',
    key: 'eitemNames',
    width: 120,
    ellipsis: true,
    showCol: true
  },
  {
    title: '检查号',
    align: 'center',
    dataIndex: 'idx',
    key: 'idx',
    width: 100,
    ellipsis: true,
    showCol: true
  },
  {
    title: '图像数',
    align: 'center',
    dataIndex: 'fileCount',
    key: 'fileCount',
    width: 80,
    showCol: true
  },
  {
    title: '图像合格率',
    align: 'center',
    key: 'qualifiedRate',
    dataIndex: 'qualifiedRate',
    width: 120,
    ellipsis: true,
    sorter: true,
    showCol: true
  },
  {
    title: '报告评分',
    align: 'center',
    key: 'reportScore',
    dataIndex: 'reportScore',
    width: 100,
    ellipsis: true,
    showCol: true
  },
  {
    title: '检查诊断',
    align: 'left',
    key: 'rptDiags',
    dataIndex: 'rptDiags',
    ellipsis: true,
    showCol: true,
    width: 160,
    customRender: ({ text }) => {
      if (text) {
        let msgs = text.replace(/<[^>]*>/g, '') //去除HTML Tag
        msgs = msgs.replace(/[|]*\n/, '') //去除行尾空格
        msgs = msgs.replace(/&nbsp;/gi, '  ') //去掉nbsp
        return msgs
      } else {
        return ''
      }
    }
  },
  {
    title: '阴阳性',
    align: 'center',
    key: 'positive',
    dataIndex: 'positive',
    width: 80,
    showCol: true,
    customRender: ({ text }) => {
      console.log('%c [ text ]-350', 'font-size:13px; background:pink; color:#bf2c9f;', text)
      if (text) {
        return h(
          'span',
          {
            style: {
              color: 'red'
            }
          },
          '阳性'
        )
      } else {
        return h(
          'span',
          {
            style: {
              color: 'green'
            }
          },
          '阴性'
        )
      }
    }
  },
  {
    title: '质控状态',
    key: 'scoreStatus',
    dataIndex: 'scoreStatus',
    ellipsis: true,
    align: 'center',
    width: 110,
    showCol: true
  },
  {
    title: '检查医院',
    align: 'center',
    dataIndex: 'hospName',
    key: 'hospName',
    ellipsis: true,
    showCol: true,
    width: 180
  },
  {
    title: '检查诊室',
    align: 'center',
    dataIndex: 'teamName',
    key: 'teamName',
    width: 100,
    showCol: true,
    ellipsis: true
  },
  {
    title: '检查医生',
    align: 'center',
    dataIndex: 'downloadDrName',
    key: 'downloadDrName',
    width: 100,
    showCol: true,
    ellipsis: true
  },
  {
    title: '检查时间',
    align: 'center',
    dataIndex: 'downloadTime',
    key: 'downloadTime',
    width: 170,
    showCol: true,
    ellipsis: true
  },
  {
    title: '完成时间',
    align: 'center',
    dataIndex: 'finishTime',
    key: 'finishTime',
    width: 170,
    showCol: true,
    ellipsis: true
  },
  {
    title: '质控医生',
    align: 'center',
    key: 'scoreCreateUserName',
    dataIndex: 'scoreCreateUserName',
    width: 100,
    showCol: true,
    ellipsis: true
  },
  {
    title: '质控时间',
    align: 'center',
    key: 'scoreCreateTime',
    dataIndex: 'scoreCreateTime',
    width: 170,
    showCol: true,
    ellipsis: true
  },
  {
    title: '审核时间',
    align: 'center',
    dataIndex: 'verifyTime',
    key: 'verifyTime',
    width: 170,
    ellipsis: true,
    showCol: true
  },
  {
    title: '高级质控',
    key: 'action',
    align: 'center',
    width: 120,
    fixed: 'right',
    showCol: true
  }
])
const storeParams = storageUtil.get('internal_params')
const formInfo = ref<FromType>({
  infirmary: true,
  hospId: '',
  hospCode: '',
  deptGUID: '',
  examEndTime: moment().endOf('d').format('YYYY-MM-DD HH:mm:ss'),
  examStartTime: '2024-07-17 00:00:0',
  positive: '',
  queryType: 0,
  queryTypeContent: '',
  scoreEndTime: '',
  scoreStartTime: '',
  scoreStatus: 'null',
  scoreUserId: '',
  patInfo: '',
  finishDrId: '',
  patSex: '',
  rcStatus: '',
  aiScoreState: true
})
if (storeParams) {
  formInfo.value = storeParams.param || {}
}
const param = ref<FromType>({
  ...cloneDeep(formInfo.value),
  positive: formInfo.value.positive ? JSON.parse(formInfo.value.positive.toString()) : '',
  scoreStatus: formInfo.value.scoreStatus ? JSON.parse(formInfo.value.scoreStatus.toString()) : null
})
const isOpen = ref(false)
const loading = ref(false)
const hospList = ref<OptionsType[]>([])
const qcDrList = ref<OptionsType[]>([])
const finishDrList = ref<ListType[]>([])
const sexList = ref<ListType[]>([])
const teamList = ref<ListType[]>([])
const examTime = ref<string[]>([formInfo.value.examStartTime, formInfo.value.examEndTime])
const scoreTime = ref<string[]>([formInfo.value.scoreStartTime, formInfo.value.scoreEndTime])

function initRange() {
  if (examTimeRef.value) {
    examTimeRef.value.initRange(examTime.value)
  }
  setTimeout(() => {
    if (isOpen.value) {
      if (examTimeCopyRef.value) {
        examTimeCopyRef.value.initRange(examTime.value)
      }
      if (scoreTimeRef.value) {
        scoreTimeRef.value.initRange(scoreTime.value)
      }
    }
  }, 20)
}

function updateOpen() {
  isOpen.value = !isOpen.value
  initRange()
}
function changeRange(dateList: Array<string>, type: string) {
  if (type === 'examTime') {
    formInfo.value.examStartTime = dateList[0] || ''
    formInfo.value.examEndTime = dateList[1] || ''
    examTime.value = dateList
  } else {
    formInfo.value.scoreStartTime = dateList[0] || ''
    formInfo.value.scoreEndTime = dateList[1] || ''
    scoreTime.value = dateList
  }
}
function hospChange(value: string | null | undefined) {
  if (value) {
    formInfo.value.hospId = value
    formInfo.value.hospCode = hospList.value.filter((item) => item.id === value)[0]?.code || ''
  } else {
    formInfo.value.hospId = ''
    formInfo.value.hospCode = ''
  }
  getTeamOption()
}
function getTeamOption() {
  getTeamList({
    hospCode: formInfo.value.hospCode || ''
  }).then((res) => {
    teamList.value = res.data || []
  })
}
function getFinishDr() {
  getFinishDrList({
    startDate: formInfo.value.examStartTime,
    endDate: formInfo.value.examEndTime
  }).then((res) => {
    finishDrList.value = res.data || []
  })
}
async function getOptionList() {
  const hospInfo = await getHospList().catch(() => {
    return {
      code: 400,
      data: []
    }
  })
  hospList.value = hospInfo.data
  getTeamOption()
  const drInfo = await getQcDrList().catch(() => {
    return {
      code: 400,
      data: []
    }
  })
  qcDrList.value = drInfo.data
  const sexInfo = await getSexList().catch(() => {
    return {
      code: 400,
      data: []
    }
  })
  sexList.value = sexInfo.data
  onSerach()
}
function enterMark(record: any) {
  console.log('%c [ record ]-555', 'font-size:13px; background:pink; color:#bf2c9f;', record)
}

const examTimeList = computed(() => [formInfo.value.examStartTime, formInfo.value.examEndTime])
const stopExamWatcher = watch(examTimeList, () => {
  getFinishDr()
})
const stopFormWatcher = watch(
  formInfo,
  () => {
    param.value = cloneDeep(formInfo.value)
    param.value.positive = formInfo.value.positive
      ? JSON.parse(formInfo.value.positive.toString())
      : ''
    param.value.scoreStatus = formInfo.value.scoreStatus
      ? JSON.parse(formInfo.value.scoreStatus.toString())
      : null
  },
  {
    deep: true
  }
)
function searchFinish(sparam: any, success: boolean) {
  console.log('%c [ sparam ]-505', 'font-size:13px; background:pink; color:#bf2c9f;', sparam)
  loading.value = false
  if (success) {
    const tempParam = {
      param: {
        ...formInfo.value
      },
      limit: sparam.limit,
      page: sparam.page,
      orderBys: sparam.orderBys
    }
    storageUtil.set('internal_params', tempParam)
  }
}
function resetForm() {
  formInfo.value = {
    infirmary: true,
    hospId: '',
    hospCode: '',
    deptGUID: '',
    examEndTime: moment().endOf('d').format('YYYY-MM-DD HH:mm:ss'),
    examStartTime: '2024-07-17 00:00:0',
    positive: '',
    queryType: 0,
    queryTypeContent: '',
    scoreEndTime: '',
    scoreStartTime: '',
    scoreStatus: 'null',
    scoreUserId: '',
    patInfo: '',
    finishDrId: '',
    patSex: '',
    rcStatus: '',
    aiScoreState: true
  }
  examTime.value = [formInfo.value.examStartTime, formInfo.value.examEndTime]
  scoreTime.value = [formInfo.value.scoreStartTime, formInfo.value.scoreEndTime]
  initRange()
  param.value = cloneDeep(formInfo.value)
  param.value.positive = formInfo.value.positive
    ? JSON.parse(formInfo.value.positive.toString())
    : ''
  param.value.scoreStatus = formInfo.value.scoreStatus
    ? JSON.parse(formInfo.value.scoreStatus.toString())
    : null
  onSerach()
}
function onSerach() {
  if (imageRef.value) {
    imageRef.value.getPage(param.value)
  }
}
onMounted(() => {
  initRange()
  getOptionList()
})
onBeforeUnmount(() => {
  stopExamWatcher()
  stopFormWatcher()
})
</script>
<style lang="scss" scoped>
#image_exam {
  @include w-h-cover();
}
</style>
